blog

Home / DeveloperSection / Blogs / Explain the concept OOPs in JavaScript

Explain the concept OOPs in JavaScript

Explain the concept OOPs in JavaScript

Ravi Vishwakarma 147 18-Jun-2024

Object-oriented programming (OOP) in JavaScript is a programming paradigm that allows you to structure your code in a way that models real-world objects and their interactions. JavaScript, while primarily a prototype-based language, supports OOP concepts such as encapsulation, inheritance, polymorphism, and abstraction through its object model. 
Here's an explanation of these concepts in the context of JavaScript:

1. Objects and Constructors
In JavaScript, objects are created using constructors or literal notation. Constructors are functions used with the new keyword to create instances of objects. Objects can contain properties (variables) and methods (functions).

// Constructor function
function Car(make, model) {
   this.make = make;
   this.model = model;
   this.drive = function() {
       console.log(`Driving ${this.make} ${this.model}`);
   };
}
// Creating instances
let myCar = new Car('Toyota', 'Corolla');
let anotherCar = new Car('Honda', 'Civic');
myCar.drive(); // Output: Driving Toyota Corolla
anotherCar.drive(); // Output: Driving Honda Civic

2. Encapsulation
Encapsulation in JavaScript involves bundling the data (properties) and methods (functions) that operate on the data into a single unit (object). This helps in hiding the internal state of objects and protecting them from outside interference.

function BankAccount(accountNumber, balance) {
   let _accountNumber = accountNumber;
   let _balance = balance;
   this.deposit = function(amount) {
       _balance += amount;
       console.log(`Deposited ${amount}. New balance: ${_balance}`);
   };
   this.withdraw = function(amount) {
       if (amount <= _balance) {
           _balance -= amount;
           console.log(`Withdrawn ${amount}. New balance: ${_balance}`);
       } else {
           console.log('Insufficient balance');
       }
   };
   this.getBalance = function() {
       return _balance;
   };
}
let myAccount = new BankAccount('12345', 1000);
myAccount.deposit(500); // Output: Deposited 500. New balance: 1500
myAccount.withdraw(200); // Output: Withdrawn 200. New balance: 1300
console.log(myAccount.getBalance()); // Output: 1300

3. Inheritance
In JavaScript, inheritance is achieved through prototype chaining. Each object has a prototype object, which acts as a template for properties and methods that the object inherits. Prototypes allow objects to inherit from other objects.

// Parent constructor
function Vehicle(make, model) {
   this.make = make;
   this.model = model;
}
// Adding a method to the prototype
Vehicle.prototype.start = function() {
   console.log(`Starting ${this.make} ${this.model}`);
};
// Child constructor inheriting from Vehicle
function Car(make, model, color) {
   Vehicle.call(this, make, model); // Call the parent constructor
   this.color = color;
}
// Inherit Vehicle's prototype
Car.prototype = Object.create(Vehicle.prototype);
Car.prototype.constructor = Car; // Set correct constructor
// Adding a method to the child prototype
Car.prototype.drive = function() {
   console.log(`Driving ${this.color} ${this.make} ${this.model}`);
};
// Creating instances
let myCar = new Car('Toyota', 'Corolla', 'blue');
myCar.start(); // Output: Starting Toyota Corolla
myCar.drive(); // Output: Driving blue Toyota Corolla

4. Polymorphism
Polymorphism in JavaScript refers to the ability of different objects to respond to the same message (method invocation) in different ways. This is achieved through method overriding and dynamic method binding.

// Parent class
class Animal {
   speak() {
       console.log('Animal makes a sound');
   }
}
// Child classes with overridden methods
class Dog extends Animal {
   speak() {
       console.log('Dog barks');
   }
}
class Cat extends Animal {
   speak() {
       console.log('Cat meows');
   }
}
// Polymorphic behavior
let dog = new Dog();
let cat = new Cat();
dog.speak(); // Output: Dog barks
cat.speak(); // Output: Cat meows

5. Abstraction
Abstraction in JavaScript involves hiding the complexity of objects and exposing only the essential features. This allows developers to work with objects at a higher level without worrying about their internal details.

// Abstract class (using function constructor)
function Shape() {
   if (this.constructor === Shape) {
       throw new Error('Cannot instantiate abstract class');
   }
}
// Abstract method
Shape.prototype.area = function() {
   throw new Error('Abstract method not implemented');
};
// Concrete classes inheriting from Shape
class Rectangle extends Shape {
   constructor(width, height) {
       super();
       this.width = width;
       this.height = height;
   }
   area() {
       return this.width * this.height;
   }
}
class Circle extends Shape {
   constructor(radius) {
       super();
       this.radius = radius;
   }
   area() {
       return Math.PI * this.radius * this.radius;
   }
}
// Using concrete classes
let rect = new Rectangle(5, 10);
console.log(rect.area()); // Output: 50
let circle = new Circle(5);
console.log(circle.area()); // Output: ~78.54

 

 

 

 

 

 

 


Hi, my self Ravi Vishwakarma. I have completed my studies at SPICBB Varanasi. now I completed MCA with 76% form Veer Bahadur Singh Purvanchal University Jaunpur. SWE @ MindStick | Software Engineer | Web Developer | .Net Developer | Web Developer | Backend Engineer | .NET Core Developer

Leave Comment

Comments

Liked By